<script setup>
import {ref, computed, watch, onActivated} from "vue";
import {useStore} from "vuex";
import {ElMessage, ElMessageBox} from "element-plus";
import {onMounted} from "vue";
import axios from "axios";
import { Plus } from '@element-plus/icons-vue'

let store = useStore();
const input1 = ref('')
const input2 = ref('')
const numArr = ref([])
const dialogKey = ref(0);
const dialogFormVisible = ref(false);
let fileToUpload = null;
let chargetype = ref([]);

const handleSelectionChange = (selection) => {
  numArr.value = selection.map(item => item.consultantId);
};


const form = ref({
  consultantId: null,
  username: '',
  password: '',
  realname: '',
  gender: '',
  phone: '',
  address: '',
  levelId:'',
  avatar: '',
  qualification: '',
  intro: '',
  age: null,
  name:'',// 咨询师等级
  chargeassociationList: [],
  consultantcertificate: [],
  consultantspecializationList: [],
});

// let chargeassociationList = store.state.consultantForm[0].chargeassociationList;
// console.log(store.state.consultantForm)

const chargeassociationList = ref([
  { chargeTypeId: '', chargeTypeName: '', price: '' }
]);

const addChargeAssociation = () => {
  chargeassociationList.value.push({ chargeTypeId: '', chargeTypeName: '', price: '' });
};

const removeChargeAssociation = (index) => {
  chargeassociationList.value.splice(index, 1);
};

const openDialog = async (row) => {
  // 初始化选项
  const resp1 = await axios.get("/chargetype/selectAllChargetype");
  chargetype.value = resp1.data.data.map(chargetype => (
      {
        chargeTypeId: chargetype.chargeTypeId,
        chargeTypeName: chargetype.chargeTypeName
      }
  ));
  // console.log(chargetype.value);
  form.value = {
    consultantId: row.consultantId,
    realname: row.realname,
    chargeassociationList: JSON.parse(JSON.stringify(row.chargeassociationList || [])) // 深拷贝以避免直接引用
  };
  // console.log("88888888888888888")
  // console.log(form.value.chargeassociationList)

  // 如果有已有的咨询方式及价格，填充到 chargeassociationList
  if (Array.isArray(form.value.chargeassociationList) && form.value.chargeassociationList.length > 0) {
    chargeassociationList.value = form.value.chargeassociationList.map(item => ({
      chargeTypeId: item.chargetype.chargeTypeId,
      chargeTypeName: item.chargetype.chargeTypeName, // 这个字段可能不需要，取决于你的需求和后端响应结构
      price: item.price
    }));
    // console.log("**************")
    // console.log(chargeassociationList.value)
  } else {
    chargeassociationList.value = [{ chargeTypeId: '', chargeTypeName: '', price: '' }];
  }

  // 显示对话框
  dialogFormVisible.value = true;
};


//前端分页
const currentPage = ref(1  );
const pageSize = ref(45); // 每页显示的条目数
const total = computed(() => store.state.consultantForm.length); // 总条目数
const ConsultantOnCurrentPage = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return store.state.consultantForm.slice(start, end);
});
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

//弹窗关闭
const handleCancel = () => {
  ElMessage({
    type: 'info',
    message: '取消操作'
  });
  dialogFormVisible.value = false;
  fileToUpload = null;
};


onMounted(async () => {
  await fetchConsultant();
});

// 重新获取所有咨询师信息的方法
const fetchConsultant = async () => {
  try {
    const resp = await axios.get("/consultant/findAllConsultant", { params: {pageNum: currentPage.value, pageSize: pageSize.value}});
    console.log(resp.data.data.list);
    const consultant = resp.data.data.list;
    store.commit("setConsultantForm", consultant);
    // const chargeassociationList = store.state.consultantForm[0].chargeassociationList;
    // console.log(chargeassociationList)
    store.commit("setOriginalConsultantForm", consultant); // 初始化原始用户列表

  } catch (err) {
    console.error(err);
  }
};

//显示全部
const resetConsultant = () => {
  store.commit('resetConsultantForm');
  currentPage.value = 1; // 重置分页回到第一页
};

//修改咨询师
const submitEdit = async () => {
  try {
    // 校验表单数据有效性
    if (form.value.realname == null) {
      ElMessage({
        type: 'warning',
        message: '请填写完整的信息'
      });
      return;
    }

    // let chargeassociationList = [];
    // for (let i = 0; i < form.value.chargeassociationList.length; i++) {
    //   const chargeassociation = chargeassociationList.value[i];
    //   if (chargeassociation.chargeTypeId && chargeassociation.price) {
    //     chargeassociationList.push({
    //       consultantId: chargeassociation.consultantId,
    //       chargeTypeId: chargeassociation.chargetype.chargeTypeId,
    //       price: chargeassociation.price
    //     });
    //   }
    // }

    // for (let i = 0; i < form.value.chargeassociationList.length; i++) {
    //   let chargeassociation = form.value.chargeassociationList[i];
    //   if (chargeassociation.chargetype && chargeassociation.price) {
    //     // 就地修改chargeassociation对象
    //     chargeassociation.chargeTypeId = chargeassociation.chargetype.chargeTypeId;
    //     delete chargeassociation.associationId;
    //     delete chargeassociation.chargetype;
    //
    //     chargeassociationList.push({
    //       consultantId: chargeassociation.consultantId,
    //       chargeTypeId: chargeassociation.chargeTypeId,
    //       price: chargeassociation.price
    //     });
    //   }
    // }

    let chargeassociationList = [];

    for (let i = 0; i < form.value.chargeassociationList.length; i++) {
      let chargeassociation = form.value.chargeassociationList[i];
      if (chargeassociation.chargetype && chargeassociation.price) {
        chargeassociation.chargeTypeId = chargeassociation.chargetype.chargeTypeId;

        // 构建新的对象而不是就地修改原始对象
        const newChargeAssociation = {
          consultantId: chargeassociation.consultantId,
          chargeTypeId: chargeassociation.chargetype.chargeTypeId,
          price: chargeassociation.price
        };
        delete chargeassociation.associationId;
        delete chargeassociation.chargetype;

        // 将新对象添加到 chargeassociationList 数组中
        chargeassociationList.push(newChargeAssociation);
      }
    }

    // 发送 PUT 请求给后端更新员工信息
    const response = await axios.put("/chargeAssociation/insertOrUpdateChargeAssociation", {
      chargeassociationList: chargeassociationList,
    });

    // 检查响应状态并处理结果
    if (response.data.code === 200) { // 假设R.ok()返回的状态码是200
      // 成功后更新Vuex store中的用户列表
      store.commit('updateChargetype', {
        ...form,
      });

      // 给出成功的消息提示
      ElMessage({
        type: 'success',
        message: '用户信息更新成功'
      });

      // 关闭对话框
      dialogFormVisible.value = false;


      await fetchConsultant();
    } else {
      // 如果有错误信息，显示错误消息
      ElMessage({
        type: 'error',
        message: response.data.message || '更新失败，请稍后再试'
      });
    }
  } catch (error) {
    console.error('更新用户时发生错误:', error);
    console.log(chargeassociationList)
    ElMessage({
      type: 'error',
      message: '更新过程中发生了错误'
    });
  }
};

//删除咨询师
const deleteConsultant = async (consultant) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
        `确定要删除咨询师 ${consultant.name} 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    // 发送 DELETE 请求给后端删除员工信息 批量删除
    const response = await axios.delete(`/consultant/deleteConsultant/${consultant.consultantId}`)

    if (response.data.code === 200) { // 假设 R.ok() 返回的状态码是 200
      // 成功后更新 Vuex store 中的用户列表
      store.commit('deleteConsultant', consultant.consultantId);

      // 给出成功的消息提示
      ElMessage({
        type: 'success',
        message: '删除成功'
      });

      //   重新获取咨询师列表
      await fetchConsultant();

    } else {
      // 如果有错误信息，显示错误消息
      ElMessage({
        type: 'error',
        message: response.data.message || '删除失败，请稍后再试'
      });
    }
  } catch (error) {
    // 如果用户取消了确认对话框，则 error.message 将包含 "cancel"
    if (error.message !== 'cancel') {
      console.error('删除咨询师时发生错误:', error);
      ElMessage({
        type: 'error',
        message: '已取消删除'
      });
    }
  }
};

//批量删除咨询师
const deleteConsultantBatch = async () => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
        `确定要删除选中的咨询师吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    // 发送 DELETE 请求给后端删除员工信息 批量删除
    await axios.delete("/consultant/deleteConsultantList", {
      data:numArr.value
    })
        .then(resp => {
          const data = resp.data.data;
          store.commit("setConsultantForm", data);
          console.log(data)
          fetchConsultant()
        })
  }
  catch (error) {
    // 如果用户取消了确认对话框，则 error.message 将包含 "cancel"
    if (error.message !== 'cancel') {
      console.error('删除咨询师时发生错误:', error);
      ElMessage({
        type: 'error',
        message: '已取消删除'
      });
    }
  }
}

//模糊搜索
const searchConsultant = async () => {
  const realname = input1.value;
  const phone = input2.value;
  const gender = input3.value;
  const levelId = input4.value;

  try {
    // 发送 GET 请求给后端模糊搜索咨询师信息
    axios.get("/consultant/findConsultantByName", {
      params: {
        realname: realname,
        phone: phone,
        gender: gender,
        levelId: levelId
      },
    })
        .then(resp => {
          const data = resp.data.data;
          store.commit("setConsultantForm", data);
          console.log(data)

          // if (data.length === 0){
          //   ElMessage({
          //     type: 'warning',
          //     message: '没有符合条件的咨询师'
          //   });
          // }

          // 重置分页到第一页
          currentPage.value = 1;

          // 更新页面上的咨询师列表
          ConsultantOnCurrentPage.value = computed(() => {
            const start = (currentPage.value - 1) * pageSize.value;
            const end = start + pageSize.value;
            return store.state.consultantForm.slice(start, end);
          });

        })
  }
  catch (error) {
    console.error('模糊搜索咨询师时发生错误:', error);
    ElMessage({
      type: 'error',
      message: '模糊搜索过程中发生了错误'
    });
  }

};

</script>

<template>
  <div>
    <div class="right-little-body">
      <div class="little-title">
        <div class="title-top">
          <div class="title-top-left">
            <span>咨询师姓名：</span>
            <div style="display: inline-block">
              <el-input
                  v-model="input1"
                  style="width: 200px"
                  size="large"
                  placeholder=""
              />
            </div>
            <span>咨询方式：</span>
            <div style="display: inline-block">
              <el-input
                  v-model="input2"
                  style="width: 200px"
                  size="large"
                  placeholder=""
              />
            </div>
          </div>
          <div class="title-top-right">
            <el-button type="primary" @click="searchConsultant">搜索</el-button>
            <el-button type="success" @click="resetConsultant">显示全部</el-button>
          </div>
        </div>
        <div class="title-middle">
          <el-button type="danger" @click="deleteConsultantBatch">批量删除</el-button>
        </div>
        <div class="title-bottom">
          <el-table :data="ConsultantOnCurrentPage"
                    stripe style="width: 1200px"
                    :border="true"
                    @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="consultantId" width="120" label="咨询师编号" />
            <el-table-column prop="realname" label="姓名"/>
            <el-table-column label="咨询方式及价格" width="240">
              <template #default="scope">
                <el-table :data="scope.row.chargeassociationList" style="width: 100%">
                  <el-table-column prop="chargetype.chargeTypeName" label="咨询方式" width="120"></el-table-column>
                  <el-table-column prop="price" label="收费标准" width="120"></el-table-column>
                </el-table>
              </template>
            </el-table-column>

            <el-table-column label="编辑">
              <template #default="scope">
                <el-button type="primary" @click="openDialog(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
            <el-table-column label="删除">
              <template #default="scope">
                <el-button type="danger" @click="deleteConsultant(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
                layout="prev, pager, next"
                :total="total"
                :page-size="pageSize"
                :current-page="currentPage"
                @current-change="handleCurrentChange"
            />
          </div>


        </div>
      </div>
      <div>
        <el-dialog
            v-model="dialogFormVisible"
            :key="dialogKey"
            title="咨询方式信息"
            width="500px"
            @before-close="handleCancel">

          <el-form :model="form">
            <el-form-item label="咨询方式及价格" :label-width="120">
              <div v-for="(charge, index) in chargeassociationList" :key="charge.id">
                <el-form-item :label="`咨询方式 ${index + 1}`" :label-width="100">

                  <el-select v-model="charge.chargeTypeId" placeholder="请选择咨询方式">
                    <el-option
                        v-for="item in chargetype"
                        :key="item.chargeTypeId"
                        :label="item.chargeTypeName"
                        :value="item.chargeTypeId" />
                  </el-select>

                  <el-input v-model="charge.price" placeholder="请输入收费标准" style="margin-left: 10px;"/>
                  <el-button type="danger" icon="el-icon-close" @click="removeChargeAssociation(index)" style="margin-left: 10px;">删除</el-button>
                </el-form-item>
              </div>
              <el-button type="primary" icon="el-icon-plus" @click="addChargeAssociation">添加</el-button>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="submitEdit">确定</el-button>
            </div>
          </template>
        </el-dialog>
      </div>


    </div>
  </div>
</template>

<style scoped>
.right-little-body {
  padding: 20px;
  width: 100%;
  position: relative;
  height: 100%;
}

.little-title {
  width: 100%;
  height: 100%;
  display: inline-block;
}

.title-top {
  width: 100%;
  height: 40px;
}

.title-top-left {
  display: inline-block;
}


.title-top-right {
  display: inline-block;
}

.title-middle {
  margin: 10px 15px;
}

.title-bottom {
  margin: 15px 15px;
}
.pagination {
  margin-top: 20px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader  {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
#el-upload{
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader #el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>